/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.weso.acota.dao;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.traversal.NodeIterator;
import org.weso.acota.to.ProviderTO;
import org.weso.acota.to.RequestSuggestionTO;
import org.weso.acota.to.SuggestionTO;
import org.weso.acota.to.TagTO;
import org.weso.acota.utils.DocumentBuilderHelper;

/**
 *
 * @author chema
 */
public class GoogleSuggestDAOImpl implements SuggestDAO {

    private static String googleUrl = "http://google.com/complete/search?output=toolbar&q=";
    private static ProviderTO defaultProvider = new ProviderTO(
    		GoogleSuggestDAOImpl.class.getSimpleName(),googleUrl);
    

    public GoogleSuggestDAOImpl() {
		super();
	}


	public SuggestionTO suggest(RequestSuggestionTO request) {
        NodeIterator it;
        try {
            for(TagTO tag:request.getSuggestions().getTags()){
            	@SuppressWarnings("static-access")
				URL url = new URL(this.googleUrl + tag.getLabel());
                ProviderTO provider = new ProviderTO(
                		GoogleSuggestDAOImpl.class.getSimpleName(),url.toURI().toString());
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setInstanceFollowRedirects(true);
                connection.setRequestProperty("Accept", "application/xml");
                if (connection.getResponseCode() == HttpURLConnection.HTTP_OK
                        && connection.getContentType().contains("text/xml"))
                {
                    InputStream is = connection.getInputStream();
                    //XML
                    SuggestionTO suggestion = new SuggestionTO();
                    Document result = DocumentBuilderHelper.getDocumentFromInputStream(is);
                    it = org.apache.xpath.XPathAPI.selectNodeIterator(result, "//suggestion/@data");
                    Node n = it.nextNode();
                    Set<TagTO> tags = new HashSet<TagTO>();
                    while(n != null){
                        tags.add(new TagTO(n.getNodeValue(),provider, request.getResource() ));
                        n = it.nextNode();
                    }
                    suggestion.setTags(tags);
                    return suggestion;
                } else {
                    throw new RuntimeException("Unable to get a representation of the resource");
                }
            }
			
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
		return null;
    }


	public ProviderTO getProvider() {
		return defaultProvider;
	}
}
